<template>
  <div class="app-container taskStatistics">
    <el-row>
      <el-col :span="3" v-if="!isWeekView">
        <el-input
          v-model="queryForm.title"
          placeholder="标题关键字"
          clearable
          style="width: 100%"
          @change="getList"
        ></el-input>
      </el-col>
      <el-col :span="5" class="mx-15px mb-15px create">
        <el-date-picker
          v-model="time"
          type="daterange"
          range-separator="至"
          style="width: 100%"
          start-placeholder="创建日期起"
          end-placeholder="创建日期止"
          value-format="YYYY-MM-DD"
          @change="getList"
          :shortcuts="shortcuts"
          :teleported="false"
          ref="datePicker"
          :clearable="!isWeekView"
        />
      </el-col>

      <el-col :span="6" class="mx-15px mb-15px dealwith" v-if="!isWeekView">
        <el-date-picker
          v-model="dealTime"
          type="daterange"
          range-separator="至"
          style="width: 100%"
          clearable
          start-placeholder="实际结束日期起"
          end-placeholder="实际结束日期止"
          value-format="YYYY-MM-DD"
          @change="getList"
          :shortcuts="shortcuts"
          :teleported="false"
          ref="datePicker"
        />
      </el-col>

      <!-- <el-col :span="3" class="mr-15px">
        <el-date-picker
          v-model="queryForm.endTime"
          type="date"
          placeholder="结束日期"
          style="width: 100%"
          clearable
          value-format="YYYY-MM-DD"
          @change="getList"
        />
      </el-col> -->
      <el-col :span="3" v-show="showSearch" class="mr-15px" v-if="!isWeekView">
        <el-select
          v-model="queryForm.statuss"
          placeholder="任务状态"
          clearable
          style="width: 100%"
          multiple
          @change="getList"
        >
          <el-option
            v-for="item in rsgl_task_status"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option> </el-select
      ></el-col>
      <el-col :span="3" v-show="showSearch" class="mr-15px" v-if="!isWeekView">
        <el-select
          v-model="queryForm.dealStatuss"
          placeholder="处理状态"
          clearable
          multiple
          style="width: 100%"
          @change="getList"
        >
          <el-option
            v-for="item in rsgl_conduct_type"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
      </el-col>
      <el-col :span="3" class="mr-15px" v-if="showSearch && !isWeekView">
        <el-select
          v-model="queryForm.belongIds"
          clearable
          multiple
          placeholder="处理人"
          style="width: 100%"
          @focus="showBelonging"
          @change="changeBelonging"
        >
          <el-option
            v-for="(item, index) in StagingData['belongIds']"
            :value="item.value"
            :label="item.label"
            :key="index"
          ></el-option
        ></el-select>
      </el-col>
      <el-col :span="3" v-show="showSearch" class="mr-15px" v-if="!isWeekView">
        <el-select
          v-model="queryForm.taskCreateIds"
          clearable
          multiple
          placeholder="创建人"
          style="width: 100%"
          @focus="showCreater"
          @change="changeCreater"
        >
          <el-option
            v-for="(item, index) in StagingData['taskCreateIds']"
            :value="item.value"
            :label="item.label"
            :key="index"
          ></el-option
        ></el-select>
      </el-col>
      <el-col :span="3" v-show="showSearch" class="mr-15px" v-if="!isWeekView">
        <el-tree-select
          v-model="queryForm.orgId"
          :data="compony"
          :props="{
            value: 'id',
            label: 'label',
            children: 'children'
          }"
          :height="208"
          style="width: 100%"
          placeholder="选择公司"
          default-expand-all
          clearable
          @change="changeCompony"
        />
      </el-col>
      <el-col :span="3" v-show="showSearch" class="mr-15px" v-if="!isWeekView">
        <el-tree-select
          v-model="queryForm.deptId"
          :data="department"
          style="width: 100%"
          :props="{
            value: 'id',
            label: 'label',
            children: 'children'
          }"
          :height="208"
          placeholder="选择部门"
          clearable
          @focus="focusDept"
          @change="getList"
        />
      </el-col>
      <el-col :span="3" v-show="showSearch" class="mr-15px" v-if="!isWeekView">
        <el-tree-select
          v-model="queryForm.businessType"
          :data="workOrderType"
          placeholder="关联业务"
          default-expand-all
          style="width: 100%"
          clearable
          @change="changeBusinessType"
        />
      </el-col>
      <el-col
        :span="3"
        v-show="showSearch"
        class="mr-15px"
        v-if="queryForm.businessType != 10 && !isWeekView"
      >
        <el-autocomplete
          v-model="name"
          :fetch-suggestions="querySearch"
          clearable
          style="width: 100%"
          placeholder="业务名称"
          @select="valueChange"
          @change="valueChange"
          @focus="promptMsg"
          multiple
          v-if="showAuto"
        />
        <el-input
          v-model="name"
          style="width: 100%"
          placeholder="业务名称"
          clearable
          v-else-if="queryForm.businessType == 8"
          @change="changeId"
          @focus="promptMsg"
        ></el-input>
        <el-select
          v-model.trim="queryForm.businessId"
          placeholder="业务名称"
          filterable
          remote
          :remote-method="queryProject"
          @change="changeBusinessId"
          @focus="promptMsg"
          clearable
          style="width: 100%"
          v-else
        >
          <el-option
            v-for="item in optionsProjectName"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-col>
      <el-col :span="3" v-show="showSearch" class="mr-15px" v-if="!isWeekView">
        <el-select
          v-model="queryForm.severity"
          clearable
          placeholder="严重程度"
          style="width: 100%"
          @change="getList"
        >
          <el-option
            v-for="(item, index) in task_severity"
            :value="item.value"
            :label="item.label"
            :key="index"
          ></el-option
        ></el-select>
      </el-col>
      <el-col v-if="isWeekView" :span="3">
        <el-input
          placeholder="选择人员"
          v-model="person"
          @click="personDialogFunc"
          style="width: 100%"
          clearable
        ></el-input>
      </el-col>
      <el-col class="mt-15px">
        <el-button @click="getList" type="primary">搜索</el-button>
        <el-button @click="reset">重置</el-button>
        <el-button icon="download" @click="exportTaskList" v-if="!isWeekView"
          >导出</el-button
        >
        <el-button icon="Crop" @click="changeView"> 切换视图 </el-button>
      </el-col>

      <!-- <el-checkbox v-model="isNowMonth">本月</el-checkbox> -->
    </el-row>
    <el-row class="my-15px flex items-center" v-if="!isWeekView">
      <span class="text-16px font-bold">总耗时(小时)：{{ totalHour }}</span>
      <right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="getList"
        :columns="clo"
      ></right-toolbar>
    </el-row>

    <el-table
      :data="tableData"
      v-loading="loading"
      stripe
      border
      @row-dblclick="handleClickProject"
      v-if="!isWeekView"
    >
      <template v-for="(item, index) in columns" :key="index">
        <el-table-column
          :key="item.key"
          :prop="item.val"
          :label="item.label"
          :width="item.width"
          :min-width="item.minWidth"
          v-if="item.visible"
          show-overflow-tooltip
        >
          <template #default="scope">
            <div v-if="item.label === '关联业务'">
              {{
                task_order_type.find(v => v.value == scope.row.businessType)
                  ?.label
              }}
            </div>
            <div v-if="item.label === '任务状态'">
              <div
                style="font-size: 12px"
                :class="
                  scope.row.status == '1'
                    ? 'orange-color'
                    : scope.row.status == '3'
                    ? 'green-color'
                    : scope.row.status == '5'
                    ? 'red-color'
                    : scope.row.status == '4'
                    ? 'blue-color'
                    : ''
                "
              >
                {{
                  rsgl_task_status.find(item => item.value == scope.row.status)
                    ? rsgl_task_status.find(
                        item => item.value == scope.row.status
                      ).label
                    : '--'
                }}
              </div>
            </div>
            <div v-if="item.label === '处理状态'">
              <div style="font-size: 12px">
                <span
                  style="font-family: '微软雅黑', sans-serif; margin-right: 5px"
                  :class="
                    scope.row.dealStatus == '1' ||
                    scope.row.dealStatus == '0' ||
                    scope.row.dealStatus == '9' ||
                    scope.row.dealStatus == '12' ||
                    scope.row.dealStatus == '13'
                      ? 'orange-color'
                      : scope.row.dealStatus == '5'
                      ? 'green-color'
                      : scope.row.dealStatus == '3'
                      ? 'red-color'
                      : scope.row.dealStatus == '2' ||
                        scope.row.dealStatus == '4'
                      ? 'blue-color'
                      : ''
                  "
                  >●</span
                >
                {{
                  dealStatusList.find(item => item.id == scope.row.dealStatus)
                    ? dealStatusList.find(
                        item => item.id == scope.row.dealStatus
                      ).name
                    : '--'
                }}
                <span v-show="scope.row.diffTime"
                  >({{ scope.row.diffTime }})</span
                >
              </div>
            </div>
          </template>
        </el-table-column>
      </template>
    </el-table>
    <pagination
      v-show="pageParams.total > 0"
      :total="pageParams.total"
      v-model:page="pageParams.pageNum"
      v-model:limit="pageParams.pageSize"
      @pagination="getList"
      v-if="!isWeekView"
    />
    <WeekView v-if="isWeekView" ref="weekViewRef" :params="weekViewParams" />
    <!-- 人员选择 -->
    <SelectDialog
      :dialog-param="dialogParam"
      @ok="selectDialogData"
      @close="closeFn"
    ></SelectDialog>
    <!-- 人员选择 -->
    <SelectDialog
      :dialog-param="personDialog"
      @ok="selectSPerson"
      @close="personDialog.isDialog = false"
    />
  </div>
</template>

<script setup name="TaskStatistics">
import { getTaskStatiscs } from '@/api/statistical/task'
import { getCurrentInstance } from 'vue'
import useCommonStore from '@/store/modules/common'
import useUserStore from '@/store/modules/user'
import { treeselect } from '@/api/rsgl/zzjg'
import { getOrdprojectNoPriv } from '@/api/projectManage/project' //项目模糊搜索
import { getOrderList } from '@/api/salesManage/contractManage' //订单模糊搜索
import { getListByCustomerName } from '@/api/customerManage/customerList' //企业客户模糊搜索
import { getBusinessOpportunityListSelect } from '@/api/salesManage/businessManage' //商机模糊搜索
import { getDetailTactlistByCactName } from '@/api/customerManage/customerList' //客户详情
import {
  getOrdpurchaseorder,
  getOrdinnerorder,
  getProjectNodeList
} from '@/api/taskManage/task'

import WeekView from './weekView'
import { format, startOfMonth, endOfMonth } from 'date-fns'
const { proxy } = getCurrentInstance()
const commonStore = useCommonStore()
const userStore = useUserStore()
console.log(userStore, 'userStore')
const {
  rsgl_task_status,
  rsgl_conduct_type,
  task_order_type, //任务类型
  system_or_project_name,
  task_severity
} = proxy.useDict(
  'rsgl_task_status',
  'rsgl_conduct_type',
  'task_order_type',
  'system_or_project_name',
  'task_severity'
)
const columns = [
  { key: 0, label: '标题', visible: true, val: 'title', minWidth: '200' },
  {
    key: 1,
    label: '实际开始日期',
    visible: false,
    val: 'realStartTime',
    width: '160'
  },
  {
    key: 2,
    label: '实际结束日期',
    visible: true,
    val: 'realEndTime',
    width: '160'
  },

  {
    key: 3,
    label: '预期开始日期',
    visible: false,
    val: 'startTime',
    width: '160'
  },
  {
    key: 4,
    label: '预期结束日期',
    visible: true,
    val: 'endTime',
    width: '160'
  },
  { key: 5, label: '任务状态', visible: true, val: 'status', width: '80' },
  {
    key: 6,
    label: '关联业务',
    visible: true,
    val: 'businessType',
    width: '90'
  },
  {
    key: 7,
    label: '业务名称',
    visible: true,
    val: 'businessName',
    width: '180'
  },
  { key: 8, label: '处理状态', visible: true, val: 'dealStatus', width: '240' },
  { key: 9, label: '处理人', visible: true, val: 'belongName', width: '80' },
  { key: 10, label: '创建单位', visible: false, val: 'orgName' },
  { key: 11, label: '创建部门', visible: false, val: 'deptName' },
  { key: 12, label: '创建人', visible: true, val: 'createName', width: '80' },
  {
    key: 13,
    label: '创建时间',
    visible: true,
    val: 'createTime',
    width: '160'
  },
  { key: 14, label: '耗时(小时)', visible: true, val: 'workHour', width: '90' }
]

const dealStatusList = [
  {
    id: '0',
    name: '待处理'
  },
  {
    id: '1',
    name: '已发起'
  },
  {
    id: '2',
    name: '已分配'
  },
  {
    id: '3',
    name: '已退回'
  },
  {
    id: '4',
    name: '转他人处理'
  },
  {
    id: '5',
    name: '已完结'
  },
  {
    id: '6',
    name: '已撤销'
  },
  {
    id: '7',
    name: '进度更新'
  },
  {
    id: '8',
    name: '结果反馈'
  },
  {
    id: '9',
    name: '处理中'
  },
  {
    id: '10',
    name: '结果反馈'
  },
  {
    id: '11',
    name: '修改任务'
  },
  {
    id: '12',
    name: '待研发处理'
  },
  {
    id: '13',
    name: '待确认'
  }
]

const projectList = ref([])
function queryList() {
  getProjectNodeList().then(res => {
    projectList.value = res.data
  })
}
queryList()
onActivated(() => {
  queryList()
})
const isNowMonth = ref()
const role = computed(
  () =>
    userStore.roles.indexOf('task_manager') > -1 ||
    userStore.roles.indexOf('admin') > -1
)

// 显隐列时强制更新
const clo = new Proxy(columns, {
  get: function (target, key) {
    proxy.$forceUpdate()
    return target[key]
  }
})

const compony = ref([])

const useTree = ref()
const workOrderType = ref([])
async function init() {
  compony.value = await commonStore.getCompanyData()
  useTree.value = await commonStore.getUseTreeData()
  workOrderType.value = arrayToTree(task_order_type.value)
  // 根据登录用户默认选择处理人
  if (!role.value) {
    queryForm.value.belongIds = [userStore.user.bindDefaultId]
    StagingData.value['belongIds'] = [
      {
        value: userStore.user.bindDefaultId,
        label: userStore.user.nickName
      }
    ]
  }
  getList()
}

/**
 * @params arr 输入数组
 * @params nodeKey 树唯一标识
 * @params parentId 父id
 *
 */
function arrayToTree(arr, nodeKey = 'value', parentId = 'parentId') {
  const mapObj = new Map()
  const result = []
  arr.forEach(v => {
    mapObj.set(v.value, v)
  })
  for (const [key, val] of mapObj) {
    if (val.parentId && mapObj.has(val.parentId)) {
      if (!mapObj.get(val.parentId).children) {
        mapObj.get(val.parentId).children = []
      }
      const some = mapObj.get(val.parentId).children.some(v => {
        return v.value === val.value
      })
      if (!some) {
        mapObj.get(val.parentId).children.push(val)
      }
    } else {
      result.push(mapObj.get(key))
    }
  }
  return result
}

const showSearch = ref(true)
const queryForm = ref({})
const time = ref()
const dealTime = ref()
const tableData = ref([])
const loading = ref(false)
const pageParams = reactive({
  total: 0,
  pageNum: 1,
  pageSize: 10
})
const totalHour = ref(0)
// 请求列表
function getList() {
  if (view.value === '周视图') {
    weekViewParams.value.searchBeginTime = time.value[0]
    weekViewParams.value.searchEndTime = time.value[1]
    if (!weekViewParams.value.belongIds) {
      delete weekViewParams.value.belongIds
    }
    proxy.$nextTick(() => {
      proxy.$refs.weekViewRef.initView()
    })
    return
  }
  if (time.value) {
    queryForm.value.startTime = time.value[0]
    queryForm.value.endTime = time.value[1]
  } else {
    queryForm.value.startTime = ''
    queryForm.value.endTime = ''
  }
  if (dealTime.value) {
    queryForm.value.endTimeS = dealTime.value[0]
    queryForm.value.endTimeE = dealTime.value[1]
  } else {
    queryForm.value.endTimeS = ''
    queryForm.value.endTimeE = ''
  }
  const params = { ...queryForm.value }
  const page = { ...pageParams }
  delete page.total
  Object.keys(params).forEach(v => {
    if (!params[v]) {
      delete params[v]
    }
    if (Array.isArray(params[v]) && !params[v].length) {
      delete params[v]
    }
  })
  // delete params.businessNames
  if (params.businessNames) {
    params.businessNames = [params.businessNames]
  }
  loading.value = true
  getTaskStatiscs(params, page)
    .then(res => {
      pageParams.total = res.total
      tableData.value = res.rows
      totalHour.value = res.msg
    })
    .finally(() => {
      loading.value = false
    })
}

const router = useRouter()
// 双击列表 查看详情
const handleClickProject = row => {
  router.push({
    path: '/rsgl/other/taskDetails',
    query: { id: row.taskId, operateId: row.id }
  })
}
// 重置
function reset() {
  if (view.value === '周视图') {
    time.value = [
      format(startOfMonth(new Date()), 'yyyy-MM-dd'),
      format(endOfMonth(new Date()), 'yyyy-MM-dd')
    ]
    weekViewParams.value = {
      searchBeginTime: time.value[0],
      searchEndTime: time.value[1]
    }
    proxy.$nextTick(() => {
      proxy.$refs.weekViewRef.initView()
    })
    return
  }
  queryForm.value = {}
  pageParams.pageNum = 1
  StagingData.value = {}
  if (time.value) {
    time.value = null
  }
  if (dealTime.value) {
    dealTime.value = null
  }
  if (!role.value) {
    queryForm.value.belongIds = [userStore.user.bindUserIds]
  }
  getList()
}

// 选择人员
const StagingData = ref({}) // 处理人下拉数据
const dialogParam = ref({
  isDialog: false, //是否弹出框
  title: '选择人员', //弹出框的标题
  multiple: true, //是否多选
  dataType: 'person',
  //   data: [], // tree的数据 如果是人员的数据的话，传dataType:'person'，data 数据可以不用
  nodeKey: 'uuid', //数据唯一值，默认是id
  checkStrictly: false, //是否遵循父子不互相关联的做法，默认为 false
  defaultCheckedKeys: []
})

// dialog确定返回数据
function selectDialogData(val) {
  console.log(val, 'fanshushuju')
  StagingData.value[val.type] = val.defaultCheckedKeys.map((v, i) => {
    return {
      value: v.replace('U', ''),
      label: val.labelData[i]
    }
  })
  queryForm.value[val.type] = val.defaultCheckedKeys.map(v =>
    v.replace('U', '')
  )
  getList()
}

function closeFn() {
  dialogParam.value.isDialog = false
}
/**  归属人员  **/
function showBelonging() {
  dialogParam.value.isDialog = true
  dialogParam.value.type = 'belongIds'
  dialogParam.value.defaultCheckedKeys = StagingData.value['belongIds']?.length
    ? StagingData.value['belongIds'].map(v => v.value)
    : []
}

// 筛选条件改变 更新
function changeBelonging(val) {
  console.log(val, 'val')
  StagingData.value['belongIds'] = StagingData.value['belongIds'].filter(v => {
    if (val.indexOf(v.value) != -1) {
      return v
    }
  })
  queryForm.value.belongIds = StagingData.value['belongIds'].map(v => v.value)
  getList()
}

/** 创建人 **/
function showCreater() {
  dialogParam.value.isDialog = true
  dialogParam.value.type = 'taskCreateIds'
  dialogParam.value.defaultCheckedKeys = StagingData.value['taskCreateIds']
    ?.length
    ? StagingData.value['taskCreateIds'].map(v => v.value)
    : []
}

// 筛选条件改变 更新
function changeCreater(val) {
  console.log(val, 'val')
  StagingData.value['taskCreateIds'] = StagingData.value[
    'taskCreateIds'
  ].filter(v => {
    if (val.indexOf(v.value) != -1) {
      return v
    }
  })
  queryForm.value.taskCreateIds = StagingData.value['taskCreateIds'].map(
    v => v.value
  )
  getList()
}

// 选择公司

const department = ref([])
function changeCompony() {
  treeselect({ parentId: queryForm.value.orgId }).then(res => {
    if (queryForm.value.orgId) {
      department.value = res.data
    } else {
      department.value = []
      queryForm.value.deptId = ''
    }
    getList()
  })
}

// 选择部门
function focusDept() {
  if (!queryForm.value.orgId) {
    proxy.$modal.msgWarning('请先选择公司')
  }
}

// 选择关联业务
function changeBusinessType(val) {
  // 清空业务名称搜选项
  queryForm.value.businessNames = ''
  name.value = ''
  queryForm.value.businessId = ''
  optionsProjectName.value = []
  getList()
}

//业务名称

// 自动补全
// 判断是否选择研发
const showAuto = computed(() => {
  // return queryParams.value.businessType.indexOf(workOrderType.value) < 0
  if (queryForm.value.businessType) {
    const findResult = workOrderType.value
      .find(v => v.value == 9)
      .children.find(child => child.value == queryForm.value.businessType)
    return findResult
  } else {
    return false
  }
})
function querySearch(queryString, cb) {
  console.log('自动补全', showAuto.value)
  const results = queryString
    ? projectList.value.filter(createFilter(queryString))
    : projectList.value
  // call callback function to return suggestions
  const data = results.map(v => {
    return {
      value: v.businessName,
      label: v.businessId
    }
  })
  cb(data)
}

const createFilter = queryString => {
  return restaurant => {
    return restaurant.businessName.indexOf(queryString) !== -1
  }
}
const name = ref()
watch(name, (newVal, oldVal) => {
  if (oldVal && !newVal) {
    queryForm.value.businessNames = ''
  }
})
// 表单赋值businessName
function valueChange(val) {
  console.log(val, 1)
  queryForm.value.businessNames = val.value
  getList()
}

function promptMsg() {
  if (!queryForm.value.businessType) {
    optionsProjectName.value = []
    proxy.$modal.msgWarning('请先选择关联业务')
    return
  }
}

// 远程检索
//关联项目名称
const optionsProjectName = ref([])
async function queryProject(val) {
  console.log('关联项目===', val, showAuto.value)
  optionsProjectName.value = []
  switch (queryForm.value.businessType) {
    case '1': //项目
      const proList = await getOrdprojectNoPriv({
        proName: val,
        pageSize: 20
      })

      if (proList.code === 200) {
        optionsProjectName.value = (proList.rows || []).map(v => ({
          label: v.proName,
          value: v.projectId
        }))
      }
      break
    case '2':
      const orderList = await getOrderList({
        title: val,
        pageSize: 20
      })

      if (orderList.code === 200) {
        optionsProjectName.value = (orderList.rows || []).map(v => ({
          label: v.title,
          value: v.id
        }))
      }
      break
    case '3': //客户
      const customerList = await getListByCustomerName({
        customer: val,
        pageSize: 20
      })

      if (customerList.code === 200) {
        optionsProjectName.value = (customerList.data || []).map(v => ({
          label: v.customerName,
          value: v.id
        }))
      }
      break
    case '4': //商机
      optionsProjectName.value = []
      const businessList = await getBusinessOpportunityListSelect({
        keyword: val,
        pageSize: 100,
        pageNum: 1
      })

      if (businessList.code === 200) {
        optionsProjectName.value = (businessList.rows || []).map(v => ({
          label: v.titleName,
          value: v.id
        }))
      }
      break
    case '5': //联系人
      optionsProjectName.value = []
      const contactsNameList = await getDetailTactlistByCactName({
        pageSize: 20,
        entId: '',
        contactName: val
      })

      if (contactsNameList.code === 200) {
        optionsProjectName.value = (contactsNameList.data || []).map(v => ({
          label: v.contactName,
          value: v.id
        }))
      }
      break
    case '6': //采购订单
      optionsProjectName.value = []
      const ordpurchaseorderList = await getOrdpurchaseorder({
        title: val,
        pageSize: 20
      })
      if (ordpurchaseorderList.code === 200) {
        optionsProjectName.value = (ordpurchaseorderList.rows || []).map(v => ({
          label: v.title,
          value: v.id
        }))
      }
      break
    case '7': //内部订单
      optionsProjectName.value = []
      const ordinonerorderList = await getOrdinnerorder({
        title: val,
        pageSize: 20
      })

      if (ordinonerorderList.code === 200) {
        optionsProjectName.value = (ordinonerorderList.rows || []).map(v => ({
          label: v.title,
          value: v.id
        }))
      }
      break
  }
}

//关联项目类型
function changeBusinessId(val) {
  queryForm.value.businessNames = optionsProjectName.value.find(
    item => item.value == val
  )?.label
  getList()
}

function changeId(val) {
  queryForm.value.businessNames = val
  getList()
}

// 导出
function exportTaskList() {
  const params = { ...queryForm.value }
  if (params.businessNames) {
    params.businessNames = [params.businessNames]
  }
  if (time.value) {
    queryForm.value.startTime = time.value[0]
    queryForm.value.endTime = time.value[1]
  } else {
    queryForm.value.startTime = ''
    queryForm.value.endTime = ''
  }
  if (dealTime.value) {
    queryForm.value.endTimeS = dealTime.value[0]
    queryForm.value.endTimeE = dealTime.value[1]
  } else {
    queryForm.value.endTimeS = ''
    queryForm.value.endTimeE = ''
  }
  Object.keys(params).forEach(v => {
    if (!params[v]) {
      delete params[v]
    }
    if (Array.isArray(params[v]) && !params[v].length) {
      delete params[v]
    }
  })

  proxy.downLoadByUrl(
    '/system/task/exportTjlist',
    params,
    `任务统计_${new Date().getTime()}.xlsx`
  )
}

init()

const shortcuts = ref({})
// 添加日期选项
addTag()
function addTag() {
  shortcuts.value = [
    {
      text: '上月',
      value: () => {
        let timing = new Date()
        const lastMonth = timing.getMonth() - 1
        const lastMonthLastDay = timing.getMonth()

        timing.setMonth(lastMonth, 1)
        const lastTime = new Date()
        lastTime.setMonth(lastMonthLastDay)
        return [
          format(timing, 'yyyy-MM-dd'),
          format(setTime('setDate', 0, lastTime), 'yyyy-MM-dd')
        ]
      }
    },
    {
      text: '本周',
      value: () => {
        let timing = new Date()
        const weekDay = timing.getDay()
        const nowTime = timing.getTime()
        let startTime, endTime
        if (weekDay !== 1) {
          if (weekDay === 0) {
            startTime = nowTime - 6 * 24 * 60 * 60 * 1000
            endTime = nowTime
          } else {
            startTime = nowTime - (weekDay - 1) * 24 * 60 * 60 * 1000
            endTime = nowTime + Math.abs(weekDay - 7) * 24 * 60 * 60 * 1000
          }
        } else {
          startTime = nowTime
          endTime = nowTime + 6 * 24 * 60 * 60 * 1000
        }
        return [format(startTime, 'yyyy-MM-dd'), format(endTime, 'yyyy-MM-dd')]
      }
    },
    {
      text: '本月',
      value: () => {
        let timing = new Date()
        const Month = timing.getMonth() + 1
        timing.setMonth(Month, 1)
        return [
          format(setTime('setDate', 1), 'yyyy-MM-dd'),
          format(setTime('setDate', 0, timing), 'yyyy-MM-dd')
        ]
      }
    }
  ]
}

function setTime(type, val, timeStamp) {
  let timing = new Date()
  if (timeStamp) {
    timing = new Date(timeStamp)
  }
  timing[type](val)
  return timing
}

const view = ref('列表视图')
// 视图修改
const weekViewParams = ref({})
const isWeekView = computed(() => view.value === '周视图')
function changeView() {
  if (view.value === '周视图') {
    view.value = '列表视图'
    time.value = []
    weekViewParams.value = {}
    person.value = ''
    proxy.$nextTick(() => {
      getList()
    })
  } else {
    view.value = '周视图'
    time.value = [
      format(startOfMonth(new Date()), 'yyyy-MM-dd'),
      format(endOfMonth(new Date()), 'yyyy-MM-dd')
    ]
    weekViewParams.value = {
      searchBeginTime: time.value[0],
      searchEndTime: time.value[1]
    }
    proxy.$nextTick(() => {
      proxy.$refs.weekViewRef.initView()
    })
  }
}
const personDialog = ref({})
function personDialogFunc() {
  personDialog.value = {
    nodeKey: 'uuid',
    isDialog: true,
    data: [useTree.value[0]],
    multiple: false,
    defaultCheckedKeys: weekViewParams.value.belongIds
      ? weekViewParams.value.belongIds.map(v => 'U' + v.replace('U', ''))
      : [],
    checkStrictly: false,
    title: '人员选择'
  }
}

const person = ref()
watch(person, val => {
  if (!val) {
    weekViewParams.value.belongIds = ''
  }
})
function selectSPerson(val) {
  person.value = val.labelData ? val.labelData.toString().trim() : ''
  personDialog.value.isDialog = false
  personDialog.value.defaultCheckedKeys = val.defaultCheckedKeys
  weekViewParams.value.belongIds = val.defaultCheckedKeys?.length
    ? val.defaultCheckedKeys.map(v => v.replace('U', ''))
    : ''

  console.log(val, weekViewParams.value)
}
</script>

<style scoped lang="scss">
.orange-color {
  color: #f59a23;
}
.blue-color {
  color: #409efc;
}
.green-color {
  color: #4bd863;
}
.red-color {
  color: red;
}
</style>

<style lang="scss">
.taskStatistics {
  .el-picker-panel__body {
    position: relative;
    display: flex;
  }
  .createuniqueselectDate {
    width: 50px;
    height: 329px;
    background-color: white;
    border-right: 1px solid #e4e7ed;
    border-top-left-radius: 5px;
    border-bottom-left-radius: 5px;
    div {
      font-size: 14px;
      cursor: pointer;
    }
  }
  .dealwithuniqueselectDate {
    width: 50px;
    height: 329px;
    background-color: white;
    border-right: 1px solid #e4e7ed;
    border-top-left-radius: 5px;
    border-bottom-left-radius: 5px;
    div {
      font-size: 14px;
      cursor: pointer;
    }
  }
}
</style>
